package com.test.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/***
 *
 * @Auther: MuYun
 * @Date: 2024/2/5 17:45
 * @Description：es的配置类
 *
 */
@Configuration
public class EsConfig {

    @Value("${es.hostlist}")
    private String host;

    @Bean(destroyMethod = "close")//spring容器关闭时销毁该bean
    public RestHighLevelClient getClient(){
        String[] hostArr = host.split(",");
        List<HttpHost> list=new ArrayList<>();
        for (int i = 0; i < hostArr.length; i++) {
            String item = hostArr[i];
            String[] itemArr = item.split(":");
            list.add(new HttpHost(itemArr[0],Integer.parseInt(itemArr[1])));
        }
        //这里就是用第一个地址来建es的客户端
        return new RestHighLevelClient(
                RestClient.builder(
                        list.toArray(new HttpHost[0])
                )
        );
    }

}
